package com.tgpms.web.common.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.tgpms.auth.security.TokenService;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.util.Common;
import com.tgpms.util.FTPUtil;
import com.tgpms.web.common.service.FTPService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 图片操作处理控制类
 * @author newway
 *
 */
@Api(value = "ImageController", tags = "图片操作处理接口")
@RestController
@CrossOrigin//此注解解决可能的跨域问题
@Slf4j
public class ImageController {
	
	//ftp_url
	@Value("${ftpparam.url}")
	private String url;
	@Value("${ftpparam.port}")
	private Integer port;
	@Value("${ftpparam.username}")
	private String username;
	@Value("${ftpparam.password}")
	private String password;
	@Value("${ftpparam.filepath5}")
	private String filepath5;
	@Value("${ftpparam.imagepath}")
	private String imagepath;
	
	@Resource
	private TokenService tokenService;
	@Autowired
	private FTPService ftpService;

	@ApiOperation(value = "tgp图片上传接口", notes = "tgp图片上传接口", httpMethod = "POST")
	@ApiImplicitParams({@ApiImplicitParam(name = "file", value = "图片", required = true, dataType = "MultipartFile"),
		@ApiImplicitParam(name = "fileProgCode", value = "屏幕编码", required = true, dataType = "String"),
		@ApiImplicitParam(name = "fileCat", value = "类型编码", required = true, dataType = "String"),
		@ApiImplicitParam(name = "fileKey", value = "屏幕主键", required = true, dataType = "String"),
		@ApiImplicitParam(name = "fileShowName", value = "图片显示名称", required = true, dataType = "String") })

	@PostMapping(value = "/ev/image/upload",headers = "content-type=multipart/form-data")
	public Result<String> upload(@RequestParam(value = "file", required = true)MultipartFile file,
			@RequestParam(value="fileProgCode",required = true)String fileProgCode,
			@RequestParam(value="fileCat",required = true)String fileCat,
			@RequestParam(value="fileKey",required = true)String fileKey,
			@RequestParam(value="fileShowName",required = true)String fileShowName,
			HttpServletRequest request) {
			InputStream in = null;
		try {
			if(fileProgCode.equals("") || fileCat.equals("") ||  fileKey.equals("") || fileShowName.equals("")) {
				return Result.ERROR(ExceptionExplain.EMPTY_BY_DATA.getExplain());
			}
			fileShowName = new String(fileShowName.getBytes("ISO-8859-1"), "UTF-8");
			String filepath = filepath5;
			//指定图片存放服务器的目录
	        String fileDir = imagepath;
	        File dir = new File(fileDir);

	        //判断目录是否存在，不存在则创建目录
	        if (!dir.exists()){
	            dir.mkdirs();
	        }
			//将上传文件转文件流
			// 获取文件名
			String fileName = file.getOriginalFilename();
			Long fileSize = file.getSize();
			// 获取文件后缀
			String suffix=fileName.substring(fileName.lastIndexOf(".")+1);
			String newfileName = fileProgCode + "_" + Common.nowTimeFomat("yyyyMMddHHmmssSSS");
			fileName = newfileName+"."+suffix;
			// 用屏幕名_时间戳作为文件名，防止生成的临时文件重复
			File excelFile = new File(dir.getAbsolutePath()+ File.separator+ fileName);
			file.transferTo(excelFile);
			in = new FileInputStream(excelFile);
			//vform插入文件信息
			Map<String, String> map = new HashMap<String, String>();
			map.put("fileProgCode", fileProgCode);
			map.put("fileCat", fileCat);
			map.put("fileKey", fileKey);
			map.put("fileShowName", fileShowName);
			map.put("fileName", fileName);
			map.put("fileSize", fileSize+"");
			map.put("uploadUser", tokenService.getUserName(request));
			Map<String,String> resMap = ftpService.addUploadFileInfo(map);
			if(resMap.get("code").equals("1")) {
				//上传文件
				if(FTPUtil.upload(url, port, username, password, filepath, in, fileName)) {
					resMap = ftpService.updateUploadFileInfo(map);
					if(resMap.get("code").equals("1")) {
						return Result.OK(ExceptionExplain.SUCCESS_BY_INFOS.getExplain(), fileName);
					}else {
						return Result.ERROR(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
					}
				}else {
					return Result.ERROR(ExceptionExplain.ERROR_BY_INSERT.getExplain());
				}
			}else {
				return Result.ERROR(ExceptionExplain.ERROR_BY_INSERT.getExplain());
			}
		} catch (IOException e) {
			e.printStackTrace();
			return Result.ERROR(ExceptionExplain.ERROR_BY_INSERT.getExplain());
		} finally {
			try {
				if(in!=null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	@ApiOperation(value = "图片预览接口", notes = "图片预览接口", httpMethod = "GET")
	@GetMapping("image/down/{imageName}")
	public String down(@PathVariable String imageName,HttpServletResponse response){
		InputStream in = null;
		OutputStream out = null;
		try {
			File dir = new File(imagepath);
			//判断目录是否存在，不存在则创建目录
	        if (!dir.exists()){
	            dir.mkdirs();
	        }
			in = new FileInputStream(new File(dir.getAbsolutePath()+ File.separator+ imageName));
			response.setContentType("image/jpeg");
            out = response.getOutputStream();  
            //读取文件流  
            int len = 0;  
            byte[] buffer = new byte[1024 * 10];  
            while ((len = in.read(buffer)) != -1){  
                out.write(buffer,0,len);  
            }  
            out.flush();  
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(in!=null) {
					in.close();
				}
				if(out!=null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	@ApiOperation(value = "tgp图片删除接口", notes = "tgp图片删除接口", httpMethod = "DELETE")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "fileProgCode", value = "屏幕编码", required = true, dataType = "String"),
		@ApiImplicitParam(name = "seqNo", value = "序号", required = true, dataType = "String"),
		@ApiImplicitParam(name = "fileKey", value = "屏幕主键", required = true, dataType = "String"),
		@ApiImplicitParam(name = "imageName", value = "图片名称", required = true, dataType = "String")
	})
	@DeleteMapping(value = "/ev/image/delete")
	public Result<String> deleteFile(@RequestParam(value = "fileKey", required = true)String fileKey,
			@RequestParam(value = "fileProgCode", required = true)String fileProgCode,
			@RequestParam(value = "seqNo", required = true)String seqNo,
			@RequestParam(value = "imageName", required = true)String imageName) {
		try {
			Map<String,String> map = ftpService.deleteFile(fileKey, fileProgCode, seqNo);
			if(map.get("code").equals("1")) {
				//删除服务器上的
			    File dir = new File(imagepath);
			    File excelFile = new File(dir.getAbsolutePath()+ File.separator+ imageName);
			    if(excelFile.delete()) {
			    	log.info(imageName+"图片服务器删除成功");
			    	if(FTPUtil.deleteFile(url, port, username, password, filepath5, imageName)) {
			    		log.info(imageName+"图片ftp删除成功");
			    	}else {
			    		log.info(imageName+"图片ftp删除失败");
			    	}
			    }else {
			    	log.info(imageName+"图片服务器删除失败");
			    }
				return Result.OK(ExceptionExplain.SUCCESS_BY_DELETE.getExplain());
			}else {
				return Result.ERROR(ExceptionExplain.ERROR_BY_DELETE.getExplain());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.ERROR(ExceptionExplain.ERROR_BY_DELETE.getExplain());
		}
	}

}
